#This script executes event-study regressions to estimate cohort-specific 
#associations between first-generation prenatal exposure to nonattainment 
#and the likelihood that first- and second-generation individuals live in 
#a different county than the first-generation county-of-birth.

rm(list=ls())
gc()
library(reldist)
library(ineq)
library(stargazer)
library(data.table)
library(dplyr)
library(dtplyr)
library(ggplot2)
library(stringdist)
library(lfe)
library(haven)
library(readr)
library(broom)
library(tidylog)
library(rdrobust)

# Set the working directory
setwd("/projects/opp_env/caa1970/")

# Source external R scripts for custom functions
source("Code/Child_Outcomes/child_outcomes_functions.R")
source("Code/rounding.r")

# Load the second-generation analysis dataset
load("Data/second_gen_college_analysis_data_jpemicro.rda")

# Event Studies

## Fig A1a - First-Generation Migration

eventA1a <- felm(adult_migrate_HS ~inst_1969+inst_1970+inst_1972+
                 inst_1973+inst_1974+inst_1975 |state_year+county_factor+year_factor+month+
                 survey_year_by_year | 0 |county_factor,
               data=regdata %>% filter(year%in%1969:1975, !is.na(all_fullterm),!is.na(parent_race), !is.na(incollege), !is.na(PI_PC))) 
summary(eventA1a)

#Save the underlying points
figA1a <- eventA1a %>% tidy() %>% mutate_each(funs(signif(.,4)),-term)  %>% 
  filter(grepl("inst", term), !is.na(estimate))%>%
  mutate(year=as.numeric(gsub("inst_","", gsub("_bin", "", term)))) %>% 
  bind_rows(., data.frame(estimate=0, std.error=0, year=1971)) %>% filter(year<=1975) 
write.csv(figA1a, file="JPE_Micro/Output/A1_Figures/FigA1a.csv", row.names=F)

## Fig A1b - Second-Generation Migration

eventA1b <- felm(child_migrate ~inst_1969+inst_1970+inst_1972+
                 inst_1973+inst_1974+inst_1975 |state_year+county_factor+year_factor+month+
                 survey_year_by_year | 0 |county_factor,
               data=regdata %>% filter(year%in%1969:1975, !is.na(all_fullterm),!is.na(parent_race), !is.na(incollege), !is.na(PI_PC))) 
summary(eventA1b)

#Save the underlying points
figA1b <- eventA1b %>% tidy() %>% mutate_each(funs(signif(.,4)),-term)  %>% 
  filter(grepl("inst", term), !is.na(estimate))%>%
  mutate(year=as.numeric(gsub("inst_","", gsub("_bin", "", term)))) %>% 
  bind_rows(., data.frame(estimate=0, std.error=0, year=1971)) %>% filter(year<=1975) 
write.csv(figA1b <- eventA1b %>% tidy() %>% mutate_each(funs(signif(.,4)),-term)  %>% 
, file="JPE_Micro/Output/A1_Figures/FigA1b.csv", row.names=F)